package com.jv.test2;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * 自定义Realm实现授权
 */
public class UserRealm extends AuthorizingRealm {

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        try {
            Class.forName("com.mysql.jdbc.Driver");

            Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/shiro", "root", "root");

            PreparedStatement prepareStatement = conn.prepareStatement("select  pwd  from  admin  where  uname =? ");

            prepareStatement.setObject(1,authenticationToken.getPrincipal());

            ResultSet rs = prepareStatement.executeQuery();

            while (rs.next()){

                SimpleAuthenticationInfo  info=new SimpleAuthenticationInfo(authenticationToken.getPrincipal(),rs.getString("pwd"),"userRealm");
                return   info;

            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        return null;
    }



     //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        String username = principalCollection.getPrimaryPrincipal().toString();

        //获得username  然后去数据库查询这个用户对应的角色，在根据角色查询出指定角色下对应的菜单，
        //返回给指定角色下的所有菜单--List集合
        System.out.println("username="+username);

        //模拟数据库查的菜单
        List<String>  list =new ArrayList<>();
        list.add("updateUser");
        list.add("addUser");
        list.add("deleteUser");

        SimpleAuthorizationInfo  simpleAuthorizationInfo=new SimpleAuthorizationInfo();

        for(String l : list){
            simpleAuthorizationInfo.addStringPermission(l);
        }

        return simpleAuthorizationInfo;
    }


}
